<template>
  <div>
    <template v-if="!initLoading && !buyError">
      <div class="order-body fade-show">
        <div class="top-bg"></div>

        <div class="cell-main flex items-center between">
          <div class="cell-main-title">配送方式</div>
          <div class="delivery-type">
            <div
              class="delivery-type-item"
              v-for="(item, index) in orderDetail.delivery_list"
              :key="index"
              :class="orderForm.delivery == item.value ? 'active' : ''"
              :style="
                orderForm.delivery == item.value
                  ? [
                      `background:${DIYTHEME?.deputy_bg};`,
                      `color:${DIYTHEME?.deputy_color}`,
                    ]
                  : []
              "
              @click="onDelivery(item.value)"
            >
              {{ item.name }}
            </div>
          </div>
        </div>

        <div class="delivery-address">
          <template v-if="orderForm.delivery == 'express'">
            <!-- 地址 -->
            <div
              class="delivery-address-main top-line"
              @click="onShowPopup('address')"
            >
              <div class="icon icon-dingwei fz-default"></div>
              <div class="delivery-address-center">
                <template v-if="!orderForm.address">
                  <div class="select-msg">请选择地址</div>
                </template>
                <template v-else>
                  <div class="flex">
                    <div class="fw">
                      {{ orderForm.address.name }}
                    </div>
                    <div class="ml5">
                      {{ orderForm.address.phone }}
                    </div>
                    <div class="address-label">
                      {{ orderForm.address.label }}
                    </div>
                    <div
                      class="address-default"
                      :style="{
                        background: DIYTHEME?.deputy_bg,
                        color: DIYTHEME?.host_bg,
                      }"
                      v-if="orderForm.address.is_default == 1"
                    >
                      默认
                    </div>
                  </div>
                  <div
                    class="delivery-address-detail mt5"
                    v-if="orderForm.address.region"
                  >
                    {{ orderForm.address.region?.city
                    }}{{ orderForm.address.region?.province
                    }}{{ orderForm.address.region?.region
                    }}{{ orderForm.address?.detail }}
                  </div>
                </template>
              </div>
              <div class="icon icon-yao-1"></div>
            </div>
          </template>
          <template v-if="orderForm.delivery == 'slef_mention'">
            <!-- 门店 -->
            <div
              class="delivery-address-main top-line"
              @click="onShowPopup('slef_mention')"
            >
              <div class="icon icon-dingwei fz-default"></div>
              <div class="delivery-address-center">
                <template v-if="!orderDetail.extract_shop?.shop_name">
                  <div class="select-msg">请选择门店</div>
                </template>
                <template v-else>
                  <div class="flex">
                    <div class="address-name">
                      {{ orderDetail.extract_shop.shop_name }}
                    </div>
                  </div>
                  <div
                    class="delivery-address-detail mt5"
                    v-if="orderDetail.extract_shop.region"
                  >
                    {{ orderDetail.extract_shop.region.city }}
                    {{ orderDetail.extract_shop.region.province }}
                    {{ orderDetail.extract_shop.region.region }}
                    {{ orderDetail.extract_shop.address }}
                  </div>
                </template>
              </div>
              <div class="icon icon-yao-1"></div>
            </div>

            <!-- 自提预留信息 -->
            <template v-if="orderDetail.extract_shop">
              <div
                class="reserve-box"
                v-if="orderForm.delivery == 'slef_mention'"
              >
                <div class="reserve-item">
                  <div class="title">您的称呼</div>
                  <input
                    placeholder="请输入您的称呼"
                    v-model="orderForm.linkname"
                    placeholder-class="placeholderStyle"
                  />
                </div>
                <div class="reserve-item">
                  <div class="title">预留电话</div>
                  <input
                    type="number"
                    placeholder="请输入预留电话"
                    v-model="orderForm.phone"
                    placeholder-class="placeholderStyle"
                  />
                </div>
              </div>
            </template>
          </template>
        </div>

        <!-- 订单信息 -->
        <div class="order-goods">
          <template
            v-for="(item, index) in orderDetail.goods_list"
            :key="index"
          >
            <div class="order-goods-item">
              <div class="order-goods-top">
                <image
                  :src="item.goods_image"
                  class="order-goods-image"
                  mode="aspectFill"
                ></image>
                <div class="order-goods-right">
                  <div class="order-goods-name">{{ item.goods_name }}</div>
                  <div class="text-grey fz-small">
                    规格:{{ item.goods_sku.sku_attr_text }}
                  </div>
                  <div class="flex between mt5">
                    <div class="flex items-center">
                      <money :value="item.goods_sku.price"></money>
                      <money
                        v-if="item.goods_sku.market_price > 0"
                        class="ml5"
                        market
                        :value="item.goods_sku.market_price"
                      ></money>
                    </div>
                    <div>x{{ item.total_num }}</div>
                  </div>
                </div>
              </div>
              <div class="flex mt5">
                <div
                  class="goods-buy-limit"
                  v-if="item.buy_limit_status && item.buy_limit > 0"
                >
                  <div>限购</div>
                  <div class="ml4">{{ item.buy_limit }}件</div>
                </div>
                <div
                  class="goods-buy-least"
                  v-if="item.buy_least_status && item.buy_least > 0"
                >
                  <div>起购</div>
                  <div class="ml4">{{ item.buy_least }}件</div>
                </div>
              </div>
            </div>
          </template>

          <div class="cell-item">
            <div class="title">配送方式</div>
            <div class="desc"></div>
            <div
              class="cell-right nowrap"
              v-if="orderForm.delivery == 'express' && orderDetail.express"
            >
              <div class="flex end">
                <div>快递配送</div>
                (
                <div class="flex" v-if="orderDetail.express?.is_free == 0">
                  <div>运费:</div>
                  <money :value="orderDetail.express.price"></money>
                </div>
                <div class="text-red" v-else>包邮</div>
                )
              </div>
            </div>
            <div class="cell-right" v-if="orderForm.delivery == 'slef_mention'">
              上门自提
            </div>
          </div>

          <div class="order-total-price flex mt5 mb5 end items-center">
            <div class="">共{{ orderDetail.order_total_num }}件商品</div>
            <div class="ml5">小计：</div>
            <money :value="orderDetail.order_total_price"></money>
          </div>
        </div>

        <!-- 备注 -->
        <div class="cell-main">
          <div>
            <div class="cell-main-title">备注留言</div>
            <input
              placeholder="请备注内容"
              v-model="orderForm.remark"
              class="mt5 mb5"
              placeholder-class="placeholderStyle"
            />
          </div>
        </div>

        <!-- 支付方式 -->
        <div class="cell-main">
          <div>
            <div class="cell-main-title">支付方式</div>
            <div class="pay-list">
              <template v-if="payments?.wechatpay == 1">
                <div class="pay-item" @click="onPayType('wechatpay')">
                  <div class="flex">
                    <div class="icon icon-wechatpay text-green"></div>
                    <div class="ml10">微信支付</div>
                  </div>
                  <div
                    class="icon icon-gouxuan text-red"
                    v-if="orderForm.pay_type == 'wechatpay'"
                  ></div>
                </div>
              </template>
              <template v-if="payments?.walletpay == 1">
                <div class="pay-item" @click="onPayType('walletpay')">
                  <div class="flex">
                    <div class="icon icon-qianbao text-orange"></div>
                    <div class="ml10">余额支付</div>
                  </div>
                  <div
                    class="icon icon-gouxuan text-red"
                    v-if="orderForm.pay_type == 'walletpay'"
                  ></div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
      <div class="order-bottom fade-show">
        <div class="order-bottom-left">
          <div>合计：</div>
          <money fw :value="orderDetail.order_pay_price"></money>
        </div>
        <div class="order-bottom-right">
          <div
            class="order-buy-btn"
            @click="toBuy"
            v-if="!orderDetail.has_error"
            :style="[
              `color:${DIYTHEME?.host_color}`,
              `background:linear-gradient(to right,${DIYTHEME?.host_bg2},${DIYTHEME?.host_bg});`,
            ]"
            :class="buyDisabled ? 'disabled' : ''"
          >
            <div v-if="buyDisabled" class="icon icon-jiazai1 mr5 spin"></div>
            <div>提交订单</div>
          </div>
          <div class="order-buy-error" v-else>提交订单</div>
        </div>
      </div>

      <!-- 地址选择 -->
      <bottomPopup
        ref="addressPopupRef"
        :mask="true"
        title="请选择您的收货地址"
      >
        <div class="address-popup-box pl10 pr10">
          <scroll-view scroll-y class="address-popup-scroll">
            <radio-group class="address-popup-list">
              <template
                v-for="(item, index) in orderDetail.address_list"
                :key="index"
              >
                <div
                  class="address-popup-item"
                  @click="onSelectedAddress(item.id)"
                >
                  <div class="address-popup-left">
                    <div class="flex">
                      <div class="fw">
                        {{ item.name }}
                      </div>
                      <div class="ml5">
                        {{ item.phone }}
                      </div>
                      <div class="address-label">
                        {{ item.label }}
                      </div>
                      <div
                        class="address-default"
                        :style="{
                          background: DIYTHEME?.deputy_bg,
                          color: DIYTHEME?.host_bg,
                        }"
                        v-if="item.is_default == 1"
                      >
                        默认
                      </div>
                    </div>
                    <div class="delivery-address-detail mt5" v-if="item.region">
                      {{ item.region?.city }}{{ item.region?.province
                      }}{{ item.region?.region }}{{ item.detail }}
                    </div>
                  </div>
                  <div class="address-popup-radio">
                    <radio
                      class="radio"
                      :color="DIYTHEME?.host_bg"
                      :checked="item.id == orderForm.address.id ? true : false"
                    ></radio>
                  </div>
                </div>
              </template>
            </radio-group>
            <div
              class="address-empty"
              v-if="orderDetail?.address_list?.length == 0"
            >
              暂无地址
            </div>
          </scroll-view>
          <div
            class="save-btn absolute"
            :style="{
              background: DIYTHEME?.host_bg,
              color: DIYTHEME?.host_color,
            }"
            @click="onCreateAddress"
          >
            添加新地址
          </div>
        </div>
      </bottomPopup>

      <!-- 门店 -->
      <bottomPopup ref="shopPopupRef" :mask="true" title="请选择自提门店">
        <div class="address-popup-box pl10 pr10">
          <scroll-view scroll-y class="shop-scroll">
            <radio-group class="address-popup-list">
              <template
                v-for="(item, index) in orderDetail.shop_list"
                :key="index"
              >
                <div
                  class="address-popup-item"
                  @click="onShopSelected(item.id)"
                >
                  <image
                    class="address-popup-item-image"
                    :src="item.shop_logo"
                    mode="aspectFill"
                  ></image>
                  <div class="address-popup-left address-shop">
                    <div class="fw">
                      <div class="">{{ item.shop_name }}</div>
                    </div>
                    <div class="fz-small mt5 text-grey">
                      <span>营业时间：</span>
                      <span>{{ item.start_time }}/{{ item.end_time }}</span>
                    </div>
                    <div class="fz-small mt5 text-grey">
                      {{ item.region.city }}{{ item.region.province
                      }}{{ item.region.region }}{{ item.address }}
                    </div>
                    <div
                      class="fz-small mt5"
                      v-if="item.distance"
                      :style="{ color: DIYTHEME?.host_bg }"
                    >
                      <div class="icon icon-location"></div>
                      <div>距您有 {{ item.distance }}</div>
                    </div>
                  </div>
                  <div class="address-popup-radio">
                    <radio
                      class="radio"
                      :color="DIYTHEME?.host_bg"
                      :checked="
                        item.id == orderDetail.extract_shop.id ? true : false
                      "
                    ></radio>
                  </div>
                </div>
              </template>
            </radio-group>
            <div
              class="address-empty"
              v-if="orderDetail?.shop_list?.length == 0"
            >
              暂无地址
            </div>
          </scroll-view>
        </div>
      </bottomPopup>
    </template>
    <template v-if="buyError">
      <div class="order-buy-error-message">{{ buyErrorMsg }}</div>
    </template>
    <init-load v-if="initLoading"></init-load>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance, onMounted } from "vue";
import { Result, ResultError } from "@/types";
import { createOrderBuyNow, createOrderCart } from "@/api/order";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import { useConfig } from "@/store";
import bottomPopup from "@/components/ui/bottom-popup/index.vue";
const { DIYTHEME, payments } = storeToRefs(useConfig());

const {
  proxy,
  proxy: { $utils },
} = getCurrentInstance() as any;

const initLoading = ref<boolean>(true);

interface orderDetailType {
  address_list?: Array<any>;
  delivery_list?: Array<{
    value: string;
    name: string;
  }>;
  shop_list?: Array<any>;
  extract_shop?: any;
  goods_list?: Array<any>;
  express?: {
    price: number | string;
    error: string;
    is_free: number;
    is_express: number;
  };
  order_total_num?: number;
  order_total_price?: number;
  order_pay_price?: number;
  has_error?: boolean;
}

const orderDetail = ref<orderDetailType>({});

const buyError = ref<boolean>(false);

const buyErrorMsg = ref<string>("");

const orderForm = ref<{
  address: any;
  delivery: string;
  goods_id: number | string;
  goods_num: number;
  goods_sku_id: number | string;
  address_id: number | string;
  shop_id: number | string;
  cart_ids: string;
  remark: string;
  pay_type: string;
  linkname: string;
  phone: string;
}>({
  address: {},
  delivery: "",
  goods_id: 0,
  goods_num: 0,
  goods_sku_id: 0,
  address_id: 0,
  shop_id: 0,
  cart_ids: "",
  remark: "",
  pay_type: "",
  linkname: "",
  phone: "",
});

const toInit = () => {
  var obj: any = {
    now_buy: 1,
    address_id: orderForm.value.address_id,
    shop_id: orderForm.value.shop_id,
    delivery: orderForm.value.delivery,
  };
  let operationApi: any = null;
  initLoading.value = true;
  if (orderForm.value.goods_id > 0) {
    // 直接下单
    obj.goods_id = orderForm.value.goods_id;
    obj.goods_num = orderForm.value.goods_num;
    obj.goods_sku_id = orderForm.value.goods_sku_id;
    operationApi = createOrderBuyNow(obj);
  } else if (orderForm.value.cart_ids != "") {
    // 购物车
    obj.cart_ids = orderForm.value.cart_ids;
    operationApi = createOrderCart(obj);
  }
  operationApi
    .then((res: Result) => {
      orderForm.value.delivery = res.data.delivery;
      orderForm.value.address = res.data.address;
      orderForm.value.pay_type = res.data.pay_type;
      orderDetail.value = res.data;
      initLoading.value = false;
    })
    .catch((err: ResultError) => {
      initLoading.value = false;
      buyErrorMsg.value = err.data?.message || "未知错误";
      buyError.value = true;
      $utils.errorMsg(err);
    });
};

onShow(() => {
  toInit();
});

const buyType = ref<string>("");

onLoad((options: any) => {
  orderForm.value.cart_ids = options.ids || "";
  orderForm.value.goods_id = options.goods_id || 0;
  orderForm.value.goods_num = options.goods_num || 0;
  orderForm.value.goods_sku_id = options.goods_sku_id || 0;

  if (orderForm.value.goods_id > 0) {
    // 直接下单
    buyType.value = "buy_now";
  } else if (orderForm.value.cart_ids != "") {
    // 购物车
    buyType.value = "cart";
  }
});

const onDelivery = (val: string) => {
  orderForm.value.delivery = val;
};

const addressPopupRef = ref<HTMLElement>();

const onShowPopup = (type: string) => {
  switch (type) {
    case "coupon":
      break;
    case "address":
      proxy?.$refs["addressPopupRef"]?.open();
      break;
    case "slef_mention":
      proxy?.$refs["shopPopupRef"]?.open();
      break;
  }
};

const onSelectedAddress = (aid: number) => {
  orderForm.value.address_id = aid;
  proxy?.$refs["addressPopupRef"]?.close();
  toInit();
};

const onShopSelected = (sid: number) => {
  orderForm.value.shop_id = sid;
  proxy?.$refs["shopPopupRef"]?.close();
  toInit();
};

const onPayType = (type: string) => {
  orderForm.value.pay_type = type;
};

const buyDisabled = ref<boolean>(false);

// 下单
const toBuy = () => {
  if (!buyDisabled.value) {
    buyDisabled.value = true;
  } else {
    return false;
  }
  var obj: any = {
    address_id: orderForm.value.address_id,
    shop_id: orderForm.value.shop_id,
    delivery: orderForm.value.delivery,
    linkname: orderForm.value.linkname,
    phone: orderForm.value.phone,
    remark: orderForm.value.remark,
    pay_type: orderForm.value.pay_type,
  };
  let operationApi: any = null;
  if (orderForm.value.goods_id > 0) {
    // 直接下单
    obj.goods_id = orderForm.value.goods_id;
    obj.goods_num = orderForm.value.goods_num;
    obj.goods_sku_id = orderForm.value.goods_sku_id;
    operationApi = createOrderBuyNow(obj);
  } else if (orderForm.value.cart_ids != "") {
    // 购物车
    obj.cart_ids = orderForm.value.cart_ids;
    operationApi = createOrderCart(obj);
  }
  operationApi
    .then((res: Result) => {
      // 发起微信支付
      if (orderForm.value.pay_type == "wechatpay") {
        $utils.payment(res.data.payment, res.data);
      } else {
        toSuccess(res.data);
      }
    })
    .catch((err: ResultError) => {
      buyDisabled.value = false;
      $utils.errorMsg(err);
    });
};

/**
 * 跳转
 */
const toSuccess = (data: any) => {
  $utils.routeRedirectTo("/otherpages/order/result/index", data, "redirectTo");
};

const onCreateAddress = () => {
  $utils.routeRedirectTo("/otherpages/user/address/create");
};
</script>


<style>
page {
  background: var(--base-page);
}
</style>


<style scoped>
.order-body {
  padding-bottom: 150rpx;
}
.top-bg {
  height: 240rpx;
  width: 100%;
  position: absolute;
  top: 0;
  z-index: -1;
}

.cell-main {
  width: calc(100% - 80rpx);
  background: #fff;
  margin: 20rpx;
  padding: 20rpx;
  border-radius: var(--base-radius-default);
}

.cell-main-title {
  height: 60rpx;
  line-height: 60rpx;
  display: flex;
}
.delivery-type {
  overflow: hidden;
  display: flex;
  justify-content: space-around;
}

.delivery-type-item {
  text-align: center;
  height: 50rpx;
  line-height: 50rpx;
  background: #f0f0f0;
  position: relative;
  padding: 0 20rpx;
  z-index: 9;
  margin-right: 5rpx;
  font-size: var(--base-size-small);
  border-radius: var(--base-radius-small);
}
.delivery-address {
  width: calc(100% - 80rpx);
  margin: 0 20rpx;
  padding: 30rpx 20rpx;
  background: #fff;
  border-radius: var(--base-radius-default);
}

.delivery-address-main {
  display: flex;
  justify-content: flex-start;
  position: relative;
  align-items: center;
}
.delivery-address-center {
  width: calc(100% - 100rpx);
  margin-left: 20rpx;
}
.delivery-address-detail {
  font-size: var(--base-size-small);
  margin-top: 10rpx;
}

/*  */
.address-popup-box {
  position: relative;
  padding: 30rpx 0 150rpx;
  background: #ffffff;
}
.address-popup-scroll {
  max-height: 800rpx;
  width: 100%;
}

.address-popup-list {
  box-sizing: border-box;
  padding: 0rpx;
}
.address-popup-item {
  margin: 20rpx;
  border-radius: var(--base-radius-default);
  border: 1rpx solid #f9f9f9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  overflow: hidden;
  padding: 10rpx;
}

.address-popup-item .address-popup-left {
  width: calc(100% - 100rpx);
  margin: 30rpx 20rpx;
  position: relative;
}
.address-popup-item .address-popup-left.address-shop {
  width: calc(100% - 240rpx);
}
.address-popup-item-image {
  width: 140rpx;
  height: 140rpx;
}
.address-popup-radio {
  width: 60rpx;
  margin-right: 20rpx;
}

.save-btn {
  width: calc(100% - 40rpx);
  margin: 20rpx auto;
  text-align: center;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: var(--base-radius-default);
}

.save-btn.absolute {
  position: absolute;
  left: 20rpx;
  bottom: 20rpx;
}

.order-goods {
  border-radius: var(--base-radius-default);
  width: calc(100% - 80rpx);
  margin: 20rpx 20rpx 0;
  padding: 20rpx;
  background: #fff;
}

.order-goods-item {
  margin-bottom: 20rpx;
}
.order-goods-item:last-child {
  border: 0;
  margin-bottom: 0;
}

.order-goods-top {
  display: flex;
  justify-content: space-between;
}
.order-goods-image {
  height: 160rpx;
  width: 160rpx;
  border-radius: var(--base-radius-small);
}
.order-goods-right {
  width: calc(100% - 180rpx);
  position: relative;
}

.order-goods-name {
  height: 76rpx;
  line-height: 38rpx;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.cell-item {
  height: 100rpx;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border-top: 1rpx solid #f9f9f9;
}

.cell-item .title {
  width: 130rpx;
}

.cell-item .desc {
  width: 40%;
  color: var(--gray);
}

.cell-item .icon {
  width: 30rpx;
  text-align: right;
  font-size: var(--base-size-small);
}

.cell-item .cell-right {
  width: calc(60% - 140rpx);
  text-align: right;
  white-space: nowrap;
}

.cell-item .coupon-text {
  font-size: var(--base-size-small);
}

.input-box {
  margin: 20rpx;
  padding: 30rpx 20rpx;
  background: #fff;
  border-radius: var(--base-radius-default);
}

.order-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  height: 80rpx;
  width: calc(100% - 40rpx);
  padding: 20rpx;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 99;
}
.order-bottom-left {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.order-total-num {
  margin-left: 10rpx;
}
.order-buy-error {
  height: 70rpx;
  line-height: 70rpx;
  padding: 0 40rpx;
  border-radius: var(--base-radius-small);
  margin: 0 20rpx;
  flex: 1;
  text-align: center;
  background: #f0f0f0;
  color: #000000;
}
.order-buy-error-message {
  line-height: 300rpx;
  text-align: center;
  color: var(--base-grey);
}

.order-buy-btn {
  height: 70rpx;
  line-height: 70rpx;
  padding: 0 40rpx;
  border-radius: 5rpx;
  flex: 1;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}
.order-buy-btn.disabled {
  opacity: 0.7;
}
.pay-list {
  width: 100%;
}
.pay-item {
  display: flex;
  justify-content: space-between;
  height: 100rpx;
  line-height: 100rpx;
  width: 100%;
}
.pay-item .icon {
  font-size: var(--base-size-large-xx);
}

.reserve-box {
  margin-top: 40rpx;
}
.reserve-box .reserve-item {
  border-top: 1rpx solid #f9f9f9;
  display: flex;
  justify-content: space-between;
  height: 120rpx;
  line-height: 120rpx;
}
.reserve-box .reserve-item .title {
  width: 130rpx;
  font-size: var(--base-size-small);
}
.reserve-box .reserve-item input {
  width: calc(100% - 130rpx);
  background: #f9f9f9;
  margin-top: 25rpx;
  height: 70rpx;
  line-height: 70rpx;
  border-radius: var(--base-radius-default);
  padding: 0 20rpx;
}

.address-empty {
  text-align: center;
  line-height: 100rpx;
  color: var(--base-grey);
}
</style>